local Icetip = _G.Icetip

function Icetip:OnEnable()
	--self:RawHook(GameTooltip, "FadeOut", "GameTooltipFadeOut", true);
	--self:RawHook(GameTooltip, "Hide", "GameTooltipHide", true);
	self:RawHookScript(GameTooltip, "OnShow", "GameTooltipOnShow");
end


local updateExistenceFrame = CreateFrame("Frame")
local updateAlphaFrame = CreateFrame("Frame")

local checkExistence = function()
	if not UnitExists("mouseover") then
		updateExistenceFrame:SetScript("OnUpdate", nil)
		local kind
		if GameTooltip:IsOwned(UIParent) then
			kind = 2
		else
			kind = 1
		end
		if kind == 2 then
			GameTooltip:FadeOut()
		else
			GameTooltip:Hide()
		end
	end
end

local checkTooltipAlpha = function()
	if GameTooltip:GetAlpha() < 1 then
		updateAlphaFrame:SetScript("OnUpdate", nil)
		local kind
		if GameTooltip:IsOwned(UIParent) then
			kind = 2
		else
			kind = 1
		end
		if kind == 2 then
			GameTooltip:FadeOut()
		else
			GameTooltip:Hide()
		end
	end
end

function Icetip:GameTooltipOnShow(...)
	if not self.justShow then
		if UnitExists("mouseover") then
			updateExistenceFrame:SetScript("OnUpdate", checkExistence)
		else
			updateAlphaFrame:SetScript("OnUpdate", checkTooltipAlpha)
		end
	end
	self.hooks[GameTooltip].OnShow(...)
end

function Icetip:GameTooltipFadeOut(this, ...)
	if self.justFade then
		self.justFade = nil
		self.hooks[this].FadeOut(this, ...)
		return
	end
	local kind
	if self.isUnit then
		if GameTooltip:IsOwned(UIParent) then
			kind = 2
		else
			kind = 1
		end
		self.isUnit = nil
	else
		if GameTooltip:IsOwned(UIParent) then
			kind = 2
		else
			kind = 1
		end
	end
	if kind == 2 then
		self.hooks[this].FadeOut(this, ...)
	else
		self.justHide = true
		GameTooltip:Hide()
	end
end

function Icetip:GameTooltipHide(this, ...)
	if self.justHide then
		self.justHide = nil
		return self.hooks[this].Hide(this, ...)
	end
	local kind
	if self.isUnit then
		if GameTooltip:IsOwned(UIParent) then
			kind =2
		else
			kind = 1
		end
		self.isUnit = nil
	else
		if GameTooltip:IsOwned(UIParent) then
			kind = 2
		else
			kind = 1
		end
	end
	if kind == 2 then
		StarTip:OnTooltipHide()
		self.justFade = true
		return GameTooltip:FadeOut()
	else
		return self.hooks[this].Hide(this, ...)
	end
end


--[[ Eva ]] --

Icetip.OnEnabled = {
	Enabled = true,
	RequestTypes = {"Event"},
	Events = {"PLAYER_LOGIN"},
	Commands = {
		{Function = Icetip:OnEnable() },
	},
}

Icetip:Add(EVA.Block:New(Icetip.OnEnabled));